const express = require('express')
const router = express.Router()
const userDB = require('../../db/user')
const multer = require('multer')
const fs = require('fs')
const path = require('path')

// multer上传保存至硬盘
const storage = multer.diskStorage({
  // 文件存放地址
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../../public/files/img/avatar'))
  },
  // 文件名命名
  filename: function (req, file, cb) {
    // const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    // cb(null, file.fieldname + '-' + uniqueSuffix)
    let ext = /png/.test(file.mimetype) ? '.png' : '.jpg'
    let fileName = req.session.userInfo._id + Date.now().toString(32) + ext
    req.fileName = fileName
    cb(null, fileName)
  }
})

const upload = multer({ storage: storage }).single("file")

// 鉴权
router.use((req, res, next) => {
  if(!req.session.userInfo){
    return res.send({
      code: 1,
      msg: '用户未登录'
    })
  }

  next()
})

// 修改用户名
router.post('/name', async (req, res) => {
  let {user} = req.body
  let reg = /^[^\s]{2,8}$/
  
  if(!reg.test(user)){
    return res.send({
      code: 2,
      msg: '非法用户名'
    })
  }

  let doc = await userDB.findOne({user})
  if(doc){
    return res.send({
      code: 1,
      msg: '用户名已存在'
    })
  }

  // 更新数据库
  await userDB.updateOne({user:req.session.userInfo.user}, {user})
  // 更新session
  req.session.userInfo.user = user
  // 返回前端
  res.send({
    code: 0,
    msg: '用户名已保存'
  })
})

// 修改密码
router.post('/pass', async (req, res) => {
  let {oldPass, pass} = req.body
  let reg = /^[\w,.?;<>/|\\:'"!@#$%^&*()+-]{6,16}$/
  
  if(!reg.test(pass)){
    return res.send({
      code: 2,
      msg: '密码格式不正确'
    })
  }

  let user = req.session.userInfo.user
  let doc = await userDB.findOne({user})
  if(doc.pass !== oldPass){
    return res.send({
      code: 1,
      msg: '原密码错误'
    })
  }

  // 修改密码
  await userDB.updateOne({user}, {pass})
  
  // 清除session
  req.session.destroy()

  // 返回前端
  res.send({
    code: 0,
    msg: '密码修改成功'
  })
})

// 更新用户头像
router.post('/avatar', async (req, res) => {
  upload(req, res, async function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
      return res.send({
        code: 1,
        msg: 'A Multer error occurred when uploading.'
      })
    } else if (err) {
      // An unknown error occurred when uploading.
      return res.send({
        code: 2,
        msg: 'An unknown error occurred when uploading.'
      })
    }

    /* 上传过程中未发生错误 */
    let user = req.session.userInfo.user   
    let doc = await userDB.findOne({user})
    let oldAvatar = doc.avatar

    // 不要删除默认头像和访客头像
    if(!/default\.png/.test(oldAvatar) && !/visitor\.png/.test(oldAvatar)){
      fs.unlink(path.join(__dirname, '../../public'+oldAvatar), ()=>{})
    }

    // 更新数据库头像地址
    let newPath = '/files/img/avatar/'+req.fileName
    await userDB.updateOne({user}, {avatar: newPath})
    
    // 更新seesion数据
    req.session.userInfo.avatar = newPath

    // 返回前端
    res.send({
      code: 0,
      msg: '头像上传成功',
      data: req.session.userInfo
    })
  })
})

module.exports = router